package cn.xx.org.service.impl;

import cn.xx.basic.service.impl.BaseServiceImpl;
import cn.xx.org.domain.Department;
import cn.xx.org.mapper.DepartmentMapper;
import cn.xx.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        // 没有选上级部门 || 选了之后清除会传递空manager对象，判断id为空
        if(department.getParent() == null || department.getParent().getId() == null) {
            // 将自增的id加到dirPath
            department.setDirPath("/" + department.getId());
        } else { // 选择了上级部门
            // 获取上级部门id
            Long parent_id = department.getParent().getId();
            // 根据上级部门id查询其dirPath
            String parent_dirPath = departmentMapper.findById(parent_id).getDirPath();
            // 设置当前对象的dirPath
            department.setDirPath(parent_dirPath + "/" + department.getId());
        }
        // 调用修改方法更新数据
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent() == null || department.getParent().getId() == null) {
            // 将自增的id加到dirPath
            department.setDirPath("/" + department.getId());
        } else { // 选择了上级部门
            // 获取上级部门id
            Long parent_id = department.getParent().getId();
            // 根据上级部门id查询其dirPath
            String parent_dirPath = departmentMapper.findById(parent_id).getDirPath();
            // 如果上级id不为空且上级id和自身id一致
            if (parent_id!=null && department.getId().equals(parent_id)){
                // dirPath就只添加入自己的id
                department.setDirPath("/" + department.getId());
                // 然后将要回显的上级id清空
                department.getParent().setId(null);
            } else {
                // 设置当前对象的dirPath
                department.setDirPath(parent_dirPath + "/" + department.getId());
            }
        }
        // 保存修改的信息
        departmentMapper.update(department);
    }

    @Override
    public void patchDel(List<Long> ids) {
        departmentMapper.patchDel(ids);
    }

    @Override
    public List<Department> findDeptTree() {
        return departmentMapper.findDeptTree();
    }
}
